package com.example.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.backend.entity.DiZhi;
import com.example.backend.mapper.DiZhiMapper;
import com.example.backend.service.IDiZhiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class DiZhiService implements IDiZhiService {
    @Autowired
    private DiZhiMapper diZhiMapper;
    /**
     新增地址*/

    @Override
    public boolean addDiZhi(DiZhi diZhi){
        return diZhiMapper.insert(diZhi)>0;
    }
    /**
     删除地址*/
    @Override
    public boolean deleteDiZhi(int dzid){
        return diZhiMapper.deleteById(dzid)>0;
    }

    /**
     修改地址*/
    @Override
    public boolean updateDiZhi(DiZhi diZhi){
        return diZhiMapper.updateById(diZhi)>0;
    }
   /**
     根据id查询地址*/
    @Override
    public DiZhi queryDiZhiById(int dzid){
        return diZhiMapper.selectById(dzid);
    }
    /**查询所有地址*/

    @Override
    public List<DiZhi> queryDizhiByYHId(Integer yhid){
        return diZhiMapper.queryDizhiByYHId(yhid);
    }
    @Override
    public List<DiZhi> queryDiZhi(){
        return diZhiMapper.selectList(null);
    }

    @Override
    public Page<DiZhi> queryDiZhiByPage(DiZhi diZhi, Integer page, Integer size, String sortField, String sortOrder) {
        LambdaQueryWrapper<DiZhi> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(diZhi.getDzid() != null, DiZhi::getDzid, diZhi.getDzid())
                .eq(diZhi.getYhid() != null, DiZhi::getYhid, diZhi.getYhid())
                .like(StringUtils.hasText(diZhi.getAddress()), DiZhi::getAddress, diZhi.getAddress());
        // 应用排序
        if (sortField != null && !sortField.isEmpty()) {
            // 需要实现字段映射方法
            SFunction<DiZhi, ?> column = getColumnByField(sortField);
            if (column != null) {
                wrapper.orderBy(true, "asc".equalsIgnoreCase(sortOrder), column);
            }
        }

        // 执行分页查询
        return diZhiMapper.selectPage(new Page<>(page, size), wrapper);
    }
    private SFunction<DiZhi, ?> getColumnByField(String field) {
        switch (field) {
            case "dzid":
                return DiZhi::getDzid;
            case "yhid":
                return DiZhi::getYhid;
            case "address":
                return DiZhi::getAddress;
            default:
                return null;
        }
    }

}
